<?php

namespace App\Services;

use Carbon\Carbon;
use App\Models\News;
use App\Models\Video;
use App\Models\CultureVoice;
use App\Models\StatisticLog;
use App\Models\CulturalHeritage;

class StatisticLogService
{

    public function updateClickNum($param = null)
    {

        // 开启事务
        \DB::transaction(function () use ($param) {

            switch ($param['type']) {
                case 1:
                    // 非遗
                    $model = CulturalHeritage::where('id', $param['res_id']);
                    break;
                case 2:
                case 3:
                    // 2、文化信息 3、新闻资讯
                    $model = News::where('id', $param['res_id']);
                    break;
                case 4:
                    $model = CultureVoice::where('id', $param['res_id']);
                    break;
                case 5:
                    $model = Video::where('id', $param['res_id']);
                    break;
                default:
                    break;
            }
            $result = null;
            if ($model) {
                $result = $model->update(['click_num' => \DB::raw('click_num + 1')]);
            }
            if ($result) {
                $currentDay = Carbon::now()->toDateString();

                StatisticLog::updateOrCreate([
                    'type' => $param['type'],
                    'res_id' => $param['res_id'],
                    'user_id' => $param['user_id'],
                    'user_ip' => $param['user_ip'],
                    'click_date' => $currentDay,
                ], [
                    'click_num' => \DB::raw('click_num + 1'),
                ]);
            }
            return $result;

        });
    }

}
